const cloud = require('wx-server-sdk');
cloud.init();

const db = cloud.database();

exports.main = async (event, context) => {
  const { date } = event;
  const wxContext = cloud.getWXContext();

  try {
    // 查重
    const checkRes = await db.collection('checkin_sign')
      .where({ _openid: wxContext.OPENID, date })
      .get();

    if (checkRes.data.length > 0) {
      return { success: false, message: '今日已签到' };
    }

    // 新增签到
    await db.collection('checkin_sign').add({
      data: {
        _openid: wxContext.OPENID,
        date
      }
    });

    // 统计签到总数
    const totalRes = await db.collection('checkin_sign')
      .where({ _openid: wxContext.OPENID })
      .count();

    return {
      success: true,
      totalCheckInDays: totalRes.total
    };

  } catch (err) {
    console.error('云函数 signIn 出错:', err);
    return {
      success: false,
      message: '服务器错误',
      error: err
    };
  }
};
